package com.china08.yxyapi.api.manage.sch.platform.xiaoben.catalog;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsSchoolCatalog;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.repository.db.YxyLessonsSchoolCatalogRepository;

/**
 * 校本课程--添加子分类
 * 
 * @author LiuWeidong
 *
 */

@CrossOrigin
@RestController
public class XiaobenCatalogTwoAddController extends YxyApiBaseController {

    @Autowired
    private YxyLessonsSchoolCatalogRepository yxyLessonsSchoolCatalogRepository;

    @RequestMapping(value = "/api_yw/manage/sch/platform/xiaoben/catalog/two/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel model) {

        String nameTwo = model.nameTwo;
        String pid = model.idOne;
        Integer level = 2;
        String schoolIdOne = model.schoolIdOne;

        Integer coun = yxyLessonsSchoolCatalogRepository.countByPidAndLevelAndSchoolId(pid, level, schoolIdOne);
        Assert.isTrue(coun < 20, "二级分类最多添加20个，请先删除其他二级分类再添加！");

        YxyLessonsSchoolCatalog yxyLessonsSchoolCatalogs = yxyLessonsSchoolCatalogRepository.findByNameAndLevelAndPid(nameTwo, level, pid);
        Assert.isTrue(yxyLessonsSchoolCatalogs == null, "请不要添加重复的子分类名称！");

        YxyLessonsSchoolCatalog yxyLessonsSchoolCatalog = new YxyLessonsSchoolCatalog();
        yxyLessonsSchoolCatalog.setLevel(level);
        yxyLessonsSchoolCatalog.setName(nameTwo);
        yxyLessonsSchoolCatalog.setPid(pid);
        yxyLessonsSchoolCatalog.setSchoolId(schoolIdOne);

        yxyLessonsSchoolCatalogRepository.save(yxyLessonsSchoolCatalog);

    }

    /** 请求参数 */
    protected static class ReqModel extends YxyApiReqModel {

        // 父类ID
        public String idOne;
        // 子类名称
        public String nameTwo;
        // 一级学校ID
        public String schoolIdOne;

    }
}
